package api.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;

public class BevisHtmlEmail extends HtmlEmail {

    @Override
    public MultiPartEmail attach(DataSource ds, String name, String description, String disposition) throws EmailException {
        if (StringUtils.isBlank(name)) {
            name = ds.getName();
        }
        final BodyPart bodyPart = createBodyPart();
        try {
            bodyPart.setDisposition(disposition);
            //  解决commons.mail.HtmlEmail附件中文名乱码问题
            bodyPart.setFileName(name);
            bodyPart.setDescription(description);
            bodyPart.setDataHandler(new DataHandler(ds));
            getContainer().addBodyPart(bodyPart);
        } catch (final Exception me) {
            throw new EmailException(me);
        }
        setBoolHasAttachments(true);

        return this;
    }
}
